import { stringify } from 'querystring';
import type { Reducer, Effect } from 'umi';
import { history } from 'umi';

import { login } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';

export type StateType = {
  loginSuccess?: boolean;
  status?: 0 | -1;
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
  id?: number;
};

export type LoginModelType = {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
};

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    loginSuccess: false,
    status: undefined,
    id: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(login, payload);
      // 存储后端返回的token
      if (response.token) {
        localStorage.setItem('admin_token', response.token);
        localStorage.setItem('admin_id', response.id);
      }
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.code === 200 && response.id) {
        // const urlParams = new URL(window.location.href);
        // const params = getPageQuery();
        message.success('🎉 🎉 🎉  登录成功！');
        // let { redirect } = params as { redirect: string };
        // if (redirect) {
        //  alert(redirect)
        //   const redirectUrlParams = new URL(redirect);
        //   if (redirectUrlParams.origin === urlParams.origin) {
        //     redirect = redirect.substr(urlParams.origin.length);
        //     if (window.routerBase !== '/') {
        //       redirect = redirect.replace(window.routerBase, '/');
        //     }
        //     if (redirect.match(/^\/.*#/)) {
        //       redirect = redirect.substr(redirect.indexOf('#') + 1);
        //     }
        //   } else {
        //     window.location.href = '/';
        //     return;
        //   }
        // }
        // history.replace(redirect || '/');
        history.replace('/');
      } else {
        return;
      }
    },

    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      localStorage.removeItem('admin_id');
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.role);
      return {
        ...state,
        status: payload.status,
        id: payload?.id,
        loginSuccess: payload.id ? true : false,
      };
    },
  },
};

export default Model;
